<script lang="ts" setup>
import { addTreeHoleApi, getTreeHolePageApi, type TreeHole } from '@/request/api/tree_hole'
import { useSystemStore } from '@/stores/system'
import type { PageDTO, PageVO, ResultType } from '@/type/type'

const systemStore = useSystemStore()
const url = systemStore.getRandomImg()

const treeHoleBoxRef = ref<HTMLElement>()
const requestAnimationFrame = window.requestAnimationFrame
const cancelAnimationFrame = window.cancelAnimationFrame
let frameId = 0

/* 查询参数 */
const page = reactive<PageDTO>({
  current: 1,
  size: 14,
  param: new Map<string, any>()
})

const getList = () => {
  getTreeHolePageApi(page).then((res: ResultType<PageVO<TreeHole>>) => {
    if (res.data != null && res.data.list.length > 0) {
      if (res.data.isEmpty) {
        page.current = 1
      }
      frameId = requestAnimationFrame(() => {
        insertBarrage(res.data.list)
      })
    }
  })
  page.current++
}

const insertBarrage = (list: TreeHole[]) => {
  const fragment = document.createDocumentFragment()
  for (let i = 0; i < list.length; i++) {
    // 动态创建元素a
    const child_a = document.createElement('a')
    child_a.className =
      'tree_hole min-w-[152px] p-1.5 -right-full w-fit absolute text-gray-50 bg-gray-950/80 flex flex-nowrap items-center rounded-full'
    child_a.href = 'javascript:'
    /* 3.5rem为弹幕高度，4rem为导航栏高度 */
    child_a.style.top = Math.random() * 2 + 3.5 * i + 4 + 'rem'
    // 动态创建头像img
    const child_img = document.createElement('img')
    child_img.alt = 'icon'
    child_img.className = 'size-9 rounded-full mr-1.5'
    child_img.src = list[i].avatar
    child_a.appendChild(child_img)
    // 动态创建留言文字span
    const child_span = document.createElement('span')
    child_span.className = 'message duration-500 whitespace-nowrap'
    child_span.innerText = list[i].content
    child_a.appendChild(child_span)
    // 动态创建时间span
    const child_span_time = document.createElement('span')
    child_span_time.className =
      'absolute duration-500 left-12 opacity-0 text-sm leading-4 time flex flex-col'
    child_span_time.innerHTML = '<span>' + list[i].createTime + '</span>'
    child_a.appendChild(child_span_time)

    const animation = child_a.animate(
      [
        {
          left: '100vw'
        },
        {
          left: '-50px'
        }
      ],
      {
        easing: 'linear',
        duration: Math.random() * 8000 + 15000
      }
    )
    child_a.addEventListener('mouseenter', () => {
      animation.pause()
    })
    child_a.addEventListener('mouseleave', () => {
      animation.play()
    })
    // 动画结束 移除元素
    animation.onfinish = () => {
      child_a.remove()
    }

    fragment.appendChild(child_a)
  }
  if (treeHoleBoxRef.value) {
    treeHoleBoxRef.value.appendChild(fragment)
  }
}

let interval = setInterval(() => {
  if (!systemStore.system.isLeave) {
    getList()
  } else {
    cancelAnimationFrame(frameId)
  }
}, 5000)

onMounted(() => {
  getList()
})

const text = ref<string>('')
const sendText = () => {
  if (text.value === '') {
    ElMessage.warning('请输入留言内容')
    return
  }
  addTreeHoleApi({ content: text.value })
  text.value = ''
}

onUnmounted(() => {
  clearInterval(interval)
  cancelAnimationFrame(frameId)
})
</script>

<template>
  <div class="pb-5">
    <div class="sticky top-0">
      <div
        id="treeHoleBox"
        ref="treeHoleBoxRef"
        :style="{ backgroundImage: 'url(' + url + ')' }"
        class="size-full overflow-hidden bg-no-repeat bg-cover flex items-center relative"
      >
        <div
          class="bg-gray-600/60 pl-5 pr-2 mx-auto h-12 border-2 flex items-center rounded-full relative z-40 text-base text-gray-50"
        >
          <input
            v-model="text"
            :maxlength="60"
            class="h-full focus:outline-0"
            placeholder="非礼勿言..."
          />
          <a class="p-2 flex duration-200 animate-pulse" href="javascript:" @click="sendText">
            <SvgIcon name="paper-plane" svg-class="!size-7" />
          </a>
        </div>
      </div>
    </div>
    <div class="pt-5 mt-5 z-20 h-fit relative use-theme use-transitions-colors">
      <Comment :key="-1" class="inner-box" />
    </div>
  </div>
</template>

<style lang="scss">
#treeHoleBox {
  min-height: calc(100vh);
  max-height: 100vh;
}

.tree_hole {
  &:hover {
    .message {
      opacity: 0;
    }

    .time {
      opacity: 1;
      color: #f5f5f5;
    }
  }
}
</style>
